package main

import (
	"context"
	"fmt"
	"github.com/tikv/client-go/config"
	"github.com/tikv/client-go/txnkv"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"time"
)
var succ uint32
var file uint32

func main() {
	var wg sync.WaitGroup
	t := time.Now()
	for i:=0; i<2; i++{
		wg.Add(1)
		go testupdate(&wg)
	}
	wg.Wait()
	elapsed := time.Since(t)
	fmt.Printf("commit use time = %v\n", elapsed)
	println(succ)
	println(file)
}

func testupdate(wg *sync.WaitGroup) (err error){
	defer wg.Done()
	pdaddr := "127.0.0.1:2379"
	eps := strings.Split(pdaddr, ",")
	TxnCli, err := txnkv.NewClient(context.TODO(), eps, config.Default())
	if err != nil {
		panic(err)
	}

	for i:=0; i<1000;i++{
		//t := time.Now()
		err = putkv(TxnCli, i)
		//elapsed := time.Since(t)
		//fmt.Printf("commit use time = %v\n", elapsed)
	}
	return err

}

func putkv(txncli  *txnkv.Client, i int) (err error){

	//创建事务客户端
	tx, err := txncli.Begin(context.Background())
	if err != nil {
		println(err)
		return err
	}
	//提交回滚延迟调用
	defer func() {
		if err == nil {
			err = tx.Commit(context.Background())
		}
		if err != nil {
			tx.Rollback()
			atomic.AddUint32(&file, 1)
		}else {
			atomic.AddUint32(&succ, 1)
		}
	}()
	_, err = tx.Get(context.TODO(), []byte("bucketsize"))
	err = tx.Set([]byte ("bucketsize"), []byte(strconv.Itoa(i)))
	err = tx.Set([]byte ("key"+strconv.Itoa(i)), []byte("value"+strconv.Itoa(i)))


	return err
}

